package com.qc.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qc.enity.Dish;
import com.qc.mapper.DishMapper;
import com.qc.service.IDishService;
import com.qc.service.IFridgeMapper;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import java.io.IOException;

@Service
public class FridgeMapperImpl  implements IFridgeMapper {
    @Override
    public int getCount(String bid) {
        String urlStr = "http://localhost:8000/runs/" +  bid + "/";
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                // 假设服务器返回的 HTML 中，每个文件链接是 <a href="filename"> 格式
                // 使用正则表达式匹配链接数量来估算文件数量
                Pattern pattern = Pattern.compile("<a href=\".*?\">");
                Matcher matcher = pattern.matcher(response.toString());
                int count = 0;
                while (matcher.find()) {
                    count++;
                }
                System.out.println(count);
                return count;
            } else {
                System.err.println("请求失败，响应码: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

}
